package com.lenovo.smarttraffic.ui.activity.stage7;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.CarInfo;
import com.lenovo.smarttraffic.bean.CarPeccancyBean;
import com.lenovo.smarttraffic.bean.PeccancyTypeBean;
import com.lenovo.smarttraffic.bean.UserBean;
import com.lenovo.smarttraffic.database.UserDB;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;
import com.lenovo.smarttraffic.view.SwipeListView;

import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class UserCenterActivity extends BaseActivity {

    public static WeakReference<UserCenterActivity> activity;

    public static List<UserDB> dbList = new ArrayList<>();
    public static List<Boolean> markList = new ArrayList<>();

    public static List<CarInfo.ROWSDETAILBean> carList = new ArrayList<>();
    public static List<CarPeccancyBean.ROWSDETAILBean> peccancyList = new ArrayList<>();
    public static List<PeccancyTypeBean.ROWSDETAILBean> typeList = new ArrayList<>();

    public static int userPos = 0;

    private int viewPos = 0;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbar_title;

    @BindView(R.id.listView)
    SwipeListView listView;

    private LinearLayout mInfoParent;
    private View mAvatar;
    private TextView mNameTv;
    private TextView mSexTv;
    private TextView mPhoneTv;
    private ListView mInfoLv;
    private TextView mAlertTv;

    private LinearLayout qrParent;
    private TextView qr_info;
    private ImageView qrImg;

    private Gson gson = new Gson();

    private boolean isLoading = false;

    private Handler handler = new Handler();

    public static String qrInfo;

    public static boolean isPaid = false;

    @Override
    protected int getLayout() {
        return R.layout.activity_user_center_2;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activity = new WeakReference<>(this);

        toolbar.setNavigationOnClickListener(v -> {
            if (isLoading) return;
            if (viewPos == 2 || viewPos == 3) {
                showView(1);
            } else if (viewPos == 4) {
                showView(3);
            } else finish();
        });
        toolbar_title.setText("用户中心");

        initView();

        if ((dbList = LitePal.findAll(UserDB.class)).isEmpty()) {
            HttpUtils.post("get_all_user_info",
                    new HttpUtils().setParam("UserName", MainActivity.userName),
                    response -> {
                        List<UserBean.ROWS_DETAIL> list = gson.fromJson(response.toString(), UserBean.class).getROWS_DETAIL();
                        for (int i = 0; i < list.size(); i++) {
                            new UserDB(list.get(i).getUsername(), list.get(i).getPassword(), list.get(i).getPname(),
                                    list.get(i).getPcardid(), list.get(i).getPsex(), list.get(i).getPtel(),
                                    list.get(i).getPregisterdate(), list.get(i).getRole(), list.get(i).getEmail()).save();
                        }
                        dbList = LitePal.findAll(UserDB.class);

                        initData();
                    });
        } else {
            initData();
        }

        HttpUtils.post("get_car_info", new HttpUtils().setParam("UserName", MainActivity.userName),
                response -> HttpUtils.post("get_all_car_peccancy", new HttpUtils().setParam("UserName", MainActivity.userName),
                        response2 -> HttpUtils.post("get_peccancy_type", new HttpUtils().setParam("UserName", MainActivity.userName),
                                response3 -> {
                                    carList = gson.fromJson(response.toString(), CarInfo.class).getROWS_DETAIL();
                                    peccancyList = gson.fromJson(response2.toString(), CarPeccancyBean.class).getROWS_DETAIL();
                                    typeList = gson.fromJson(response3.toString(), PeccancyTypeBean.class).getROWS_DETAIL();

                                })));
    }

    private void initData() {
        listView.setAdapter(new UserCenterAdapter(listView, false));
    }

    public void showView(int which) {
        viewPos = which;
        if (which == 1) {
            toolbar_title.setText("用户中心");
            listView.setVisibility(View.VISIBLE);
            mInfoParent.setVisibility(View.GONE);
            listView.setAdapter(new UserCenterAdapter(listView, false));
            isPaid = false;
        } else if (which == 2) {
            toolbar_title.setText("用户收藏");
            listView.setVisibility(View.VISIBLE);
            mInfoParent.setVisibility(View.GONE);
            listView.setAdapter(new UserCenterAdapter(listView, true));
        } else if (which == 3) {
            toolbar_title.setText("违章详情");
            listView.setVisibility(View.GONE);
            mInfoParent.setVisibility(View.VISIBLE);
            mInfoLv.setVisibility(View.GONE);
            mAlertTv.setVisibility(View.GONE);

            UserDB userDB = dbList.get(userPos);
            mAvatar.setBackgroundResource(userDB.getPsex().equals("男") ? R.mipmap.touxiang_2 : R.mipmap.touxiang_1);
            mNameTv.setText("姓名：" + userDB.getPname());
            mSexTv.setText("性别：" + userDB.getPsex());
            mPhoneTv.setText("手机号码：\n" + userDB.getPtel());

            new Thread(() -> {
                isLoading = true;
                List<Map<String, Object>> list = new ArrayList<>();
                boolean hasCar = false;
                for (int i = 0; i < peccancyList.size(); i++) {
                    for (int j = 0; j < carList.size(); j++) {
                        //判断有无违章
                        if (peccancyList.get(i).getCarnumber().equals(carList.get(j).getCarnumber())) {
                            if (carList.get(j).getPcardid().equals(dbList.get(viewPos).getPcardid())) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("brand", carList.get(j).getCarbrand());
                                map.put("number", peccancyList.get(i).getCarnumber());
                                map.put("addr", peccancyList.get(i).getPaddr());
                                map.put("code", peccancyList.get(i).getPcode());
                                map.put("time", peccancyList.get(i).getPdatetime().replace(" ", "\n"));
                                list.add(map);
                            }
                        }

                        //判断有无车辆
                        if (carList.get(j).getPcardid().equals(dbList.get(viewPos).getPcardid())) {
                            hasCar = true;
                        }
                    }
                }

                boolean finalHasCar = hasCar;
                runOnUiThread(() -> {
                    if (!finalHasCar) {
                        mAlertTv.setText("该用户无车辆信息");
                        mAlertTv.setVisibility(View.VISIBLE);
                    } else if (list.isEmpty()) {
                        mAlertTv.setText("恭喜你，暂无违章数据！");
                        mAlertTv.setVisibility(View.VISIBLE);
                    } else {
                        mInfoLv.setAdapter(new WeiZhangAdapter(list));
                        mInfoLv.setVisibility(View.VISIBLE);
                    }
                });

                isLoading = false;
            }).start();
        } else {
            toolbar_title.setText("违章详情");
            qrParent.setVisibility(View.VISIBLE);
            mInfoParent.setVisibility(View.GONE);
            qr_info.setVisibility(View.GONE);

            qr_info.setText(qrInfo);
            qrImg.setOnLongClickListener(v -> {
                isPaid = true;

                if (qr_info.getVisibility() == View.GONE) {
                    qr_info.setVisibility(View.VISIBLE);
                } else {
                    qr_info.setVisibility(View.GONE);
                }

                ((WeiZhangAdapter) mInfoLv.getAdapter()).notifyDataSetChanged();
                return true;
            });

            runnable.run();
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (viewPos == 4) {
                qrImg.setImageBitmap(Utils.createQRCodeImage(qrInfo + System.currentTimeMillis(), 200, 200));

                handler.postDelayed(runnable, 5000);
            }
        }
    };

    @Override
    public void onBackPressedSupport() {
        if (isLoading) return;
        if (viewPos == 2 || viewPos == 3) {
            showView(1);
        } else if (viewPos == 4) {
            showView(3);
        } else super.onBackPressedSupport();
    }

    private void initView() {
        mInfoParent = findViewById(R.id.info_parent);
        mAvatar = findViewById(R.id.avatar);
        mNameTv = findViewById(R.id.name_tv);
        mSexTv = findViewById(R.id.sex_tv);
        mPhoneTv = findViewById(R.id.phone_tv);
        mInfoLv = findViewById(R.id.info_lv);
        mAlertTv = findViewById(R.id.alert_tv);
        qrParent = findViewById(R.id.qr_parent);
        qr_info = findViewById(R.id.qr_info);
        qrImg = findViewById(R.id.qr_img);
    }
}

class UserCenterAdapter extends BaseAdapter {

    private SwipeListView listView;

    private List<UserDB> list = new ArrayList<>(UserCenterActivity.dbList);
    private List<Boolean> markList = UserCenterActivity.markList;

    private boolean hasTop = false;
    private boolean showTop;

    public UserCenterAdapter(SwipeListView listView, boolean showTop) {
        this.listView = listView;
        this.showTop = showTop;

        if (markList.isEmpty()) {
            for (int i = 0; i < list.size(); i++)
                markList.add(i, false);
        }

        if (showTop) {
            initMarkList();
        }
    }

    private void initMarkList() {
        List<UserDB> list = UserCenterActivity.dbList;
        this.list.clear();
        for (int i = 0; i < markList.size(); i++) {
            if (markList.get(i)) {
                this.list.add(list.get(i));
            }
        }

        markList = new ArrayList<>(markList);
        markList.clear();
        for (int i = 0; i < this.list.size(); i++) {
            this.markList.add(true);
        }

        if (this.list.isEmpty()) {
            ToastUtils.showToast(InitApp.getContext(), "暂无收藏条目");
        }
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_user_center, parent, false);
            holder.avatar = convertView.findViewById(R.id.avatar);
            holder.info_tv = convertView.findViewById(R.id.info_tv);
            holder.admin_tv = convertView.findViewById(R.id.admin_tv);
            holder.info_btn = convertView.findViewById(R.id.info_btn);
            holder.mark_tv = convertView.findViewById(R.id.mark_tv);

            if (showTop) {
                convertView.findViewById(R.id.swipe_container).setLayoutParams(new LinearLayout.LayoutParams(550, ViewGroup.LayoutParams.MATCH_PARENT));
                holder.top_tv = convertView.findViewById(R.id.top_tv);
                holder.top_tv.setVisibility(View.VISIBLE);
            }

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        UserDB bean = list.get(position);

        holder.avatar.setBackgroundResource(bean.getPsex().equals("男") ? R.mipmap.touxiang_2 : R.mipmap.touxiang_1);
        holder.avatar.setOnClickListener(v -> {
            if (!showTop) {
                UserCenterActivity.userPos = position;
                UserCenterActivity.activity.get().showView(3);
            }
        });

        holder.info_tv.setText("用户名：" + bean.getUsername() + "\n姓名：" + bean.getPname() + "\n电话：" + bean.getPtel());
        //holder.admin_tv.setText();

        holder.info_btn.setText(showTop ? "已收藏" : "查看详情");
        holder.info_btn.setOnClickListener(v -> {
            if (!showTop) {
                UserCenterActivity.activity.get().showView(2);
            }
        });

        if (showTop && position == 0 && hasTop) {
            convertView.setBackgroundColor(Utils.getColor(parent.getContext(), R.color.Grey));

            holder.mark_tv.setText("取消置顶");
            holder.mark_tv.setOnClickListener(v -> {
                initMarkList();
                hasTop = false;
                notifyDataSetChanged();
                listView.turnToNormal();
            });

            if (markList.get(position)) {
                holder.top_tv.setText("取消收藏");
                holder.top_tv.setOnClickListener(v -> {
                    markList.set(position, false);
                    if (showTop) {
                        initMarkList();
                    }
                    notifyDataSetChanged();
                    listView.turnToNormal();
                });
            } else {
                holder.top_tv.setText("收藏");
                holder.top_tv.setOnClickListener(v -> {
                    markList.set(position, true);
                    notifyDataSetChanged();
                    listView.turnToNormal();
                });
            }
        } else {
            convertView.setBackground(null);

            if (markList.get(position)) {
                holder.mark_tv.setText("取消收藏");
                holder.mark_tv.setOnClickListener(v -> {
                    markList.set(position, false);
                    if (showTop) {
                        initMarkList();
                    }
                    notifyDataSetChanged();
                    listView.turnToNormal();
                });
            } else {
                holder.mark_tv.setText("收藏");
                holder.mark_tv.setOnClickListener(v -> {
                    markList.set(position, true);
                    notifyDataSetChanged();
                    listView.turnToNormal();
                });
            }

            if (showTop) {
                holder.top_tv.setText("置顶");
                holder.top_tv.setOnClickListener(v -> {
                    if (hasTop) {
                        initMarkList();
                    } else {
                        hasTop = true;
                    }
                    list.add(0, list.get(position));
                    list.remove(position + 1);
                    notifyDataSetChanged();
                    listView.turnToNormal();
                });
            }
        }
        return convertView;
    }

    static class ViewHolder {
        View avatar;
        TextView info_tv, admin_tv;
        Button info_btn;

        TextView mark_tv, top_tv;
    }
}

class WeiZhangAdapter extends BaseAdapter {

    private List<PeccancyTypeBean.ROWSDETAILBean> typeList = UserCenterActivity.typeList;
    private List<Map<String, Object>> list;

    public WeiZhangAdapter(List<Map<String, Object>> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_weizhang, parent, false);
            holder.id_tv = convertView.findViewById(R.id.id_tv);
            holder.icon = convertView.findViewById(R.id.icon);
            holder.number_tv = convertView.findViewById(R.id.number_tv);
            holder.road_tv = convertView.findViewById(R.id.road_tv);
            holder.info_tv = convertView.findViewById(R.id.info_tv);
            holder.count_tv = convertView.findViewById(R.id.count_tv);
            holder.money_tv = convertView.findViewById(R.id.money_tv);
            holder.time_tv = convertView.findViewById(R.id.time_tv);
            holder.status_tv = convertView.findViewById(R.id.status_tv);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Map<String, Object> map = list.get(position);

        holder.id_tv.setText((position + 1) + "");
        holder.icon.setBackgroundResource(Utils.getCarBandRes((String) map.get("brand")));
        holder.number_tv.setText((String) map.get("number"));
        holder.road_tv.setText((String) map.get("addr"));

        for (int i = 0; i < typeList.size(); i++) {
            if (typeList.get(i).getPcode().equals(map.get("code"))) {
                PeccancyTypeBean.ROWSDETAILBean bean = typeList.get(i);
                holder.info_tv.setText(bean.getPremarks());
                holder.count_tv.setText(bean.getPscore() == 0 ? "无" : bean.getPscore() + "");
                holder.status_tv.setText("未处理");

                if (bean.getPmoney() == 0) {
                    holder.money_tv.setText("无");
                    holder.status_tv.setEnabled(false);
                    holder.status_tv.setTextColor(Utils.getColor(parent.getContext(), R.color.Grey));
                } else {
                    holder.money_tv.setText(bean.getPmoney() + "");
                    holder.status_tv.setEnabled(true);
                    if (UserCenterActivity.isPaid) {
                        holder.status_tv.setTextColor(Utils.getColor(parent.getContext(), R.color.Green));
                        holder.status_tv.setText("已处理");
                    } else {
                        holder.status_tv.setTextColor(Utils.getColor(parent.getContext(), R.color.Red));
                    }
                }

                holder.money_tv.setText(bean.getPmoney() == 0 ? "无" : bean.getPmoney() + "");
                break;
            }
        }

        holder.time_tv.setText((String) map.get("time"));

        holder.status_tv.setOnClickListener(v -> {
            if (!UserCenterActivity.isPaid) {
                UserCenterActivity.qrInfo = map.get("number") + " " + (position + 1);
                UserCenterActivity.activity.get().showView(4);
            }
        });

        return convertView;
    }

    static class ViewHolder {
        TextView id_tv;
        View icon;

        TextView number_tv, road_tv, info_tv, count_tv, money_tv, time_tv, status_tv;
    }
}
